package com.muyu.danmo.service.impl;


import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.domain.dto.DepartmentDTO;
import com.muyu.danmo.domain.dto.MajorDTO;
import com.muyu.danmo.mapper.*;
import com.muyu.danmo.req.DanmoArtCollegesReq;
import com.muyu.danmo.service.IDanmoArtCollegesService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 书画院校Service业务层处理
 *
 * @author yangle
 * @date 2024-10-31
 */
@Service
@Log4j2
public class DanmoArtCollegesServiceImpl implements IDanmoArtCollegesService {
    @Autowired
    private DanmoArtCollegesMapper danmoArtCollegesMapper;

    @Autowired
    private DanmoArtCollegesCharacteristicsMapper danmoArtCollegesCharacteristicsMapper;

    @Autowired
    private DanmoArtMaterialMapper danmoArtMaterialMapper;

    /**
     * 查询书画院校
     *
     * @param id 书画院校主键
     * @return 书画院校
     */
    @Override
    public Result selectDanmoArtCollegesById(Long id) {
//        先查询出所有的书画院校信息
        List<DanmoArtColleges> danmoArtColleges = danmoArtCollegesMapper.selectDanmoArtCollegesById(id);
//        获取第一个书画院校信息
        DanmoArtColleges danmoArtCollege = danmoArtColleges.get(0);
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        查询该用户下是否有收藏
//        如果没有收藏，则将收藏提示信息该为空字符串
        Boolean result = danmoArtMaterialMapper.selectDanmoCollectMaterialByIdAndUserId(loginUser.getUserid(), id);
        boolean isCollected = (result != null) ? result : false; // 当result为null时使用false
        if (!isCollected) {
            danmoArtCollege.setWhetherToCollect("");
        }else {
            danmoArtCollege.setWhetherToCollect("已收藏");
        }
//        DanmoArtColleges danmoArtColleges;
//        if (danmoArtMaterial == null){
//            danmoArtColleges = danmoArtCollegesMapper.selectDanmoArtCollegesById(id);
//        }else {
//            danmoArtColleges = danmoArtCollegesMapper.selectDanmoArtCollegesByIdAndUserId(id,loginUser.getUserid());
//        }
//        DanmoArtColleges danmoArtColleges = danmoArtCollegesMapper.selectDanmoArtCollegesById(id,loginUser.getUserid());
//        danmoArtColleges.setDanmoArtCollegesCharacteristicsList(danmoArtCollegesCharacteristicsMapper.selectDanmoArtCollegesCharacteristicsListByCollegesId(id));
        return Result.success(danmoArtCollege);
    }

    /**
     * 查询书画院校列表
     *
     * @param danmoArtColleges 书画院校
     * @return 书画院校
     */
    @Override
    public List<DanmoArtColleges> selectDanmoArtCollegesList(DanmoArtColleges danmoArtColleges) {
        List<DanmoArtColleges> danmoArtColleges1 = danmoArtCollegesMapper.selectDanmoArtCollegesList(danmoArtColleges);
//        for (DanmoArtColleges artColleges : danmoArtColleges1) {
//            artColleges.setDanmoArtCollegesCharacteristicsList(danmoArtCollegesCharacteristicsMapper.selectDanmoArtCollegesCharacteristicsListByCollegesId(artColleges.getId()));
//        }
        return danmoArtColleges1;

    }

    @Autowired
    private DanmoArtMajorsMapper danmoArtMajorsMapper;
    @Autowired
    private DanmoArtContentMapper danmoArtContentMapper;

    /**
     * 新增书画院校
     *
     * @param danmoArtColleges 书画院校
     * @return 结果
     */
    @Transactional
    @Override
    public Result insertDanmoArtColleges(DanmoArtColleges danmoArtColleges) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return Result.warn("请登录");
            }

            Result result = validateDanmoTrainingInformation(danmoArtColleges);
            if (result != null) {
                return result;
            }
            // 设置创建时间并插入院校信息
            danmoArtColleges.setCreateTime(DateUtils.getNowDate());
            danmoArtColleges.setUserId(loginUser.getUserid());
            danmoArtCollegesMapper.insertDanmoArtColleges(danmoArtColleges);

            // 插入相关表数据
            insertDanmoArtDoor(danmoArtColleges);
            insertDanmoArtCollegesCharacteristics(danmoArtColleges, danmoArtColleges.getId());

            // 获取院校专业列表
        List<DanmoArtDepartments> danmoDanmoArtDepartmentsList = danmoArtColleges.getDanmoDanmoArtDepartmentsList();// 提前获取ArtContent列表
        processMajors(danmoArtColleges.getId(), danmoDanmoArtDepartmentsList);

        return Result.success(danmoArtColleges, "添加成功");
    }
            @Autowired
            private DanmoArtDepartmentsMapper danmoArtDepartmentsMapper;
    private void processMajors(Long id, List<DanmoArtDepartments> danmoDanmoArtDepartmentsList) {
        for (DanmoArtDepartments danmoArtContent : danmoDanmoArtDepartmentsList) {
            danmoArtContent.setCollegeId(id);
            danmoArtDepartmentsMapper.insertDanmoArtDepartments(danmoArtContent);
            for (DanmoArtMajors danmoArtMajors : danmoArtContent.getDanmoArtMajorsList()) {
                danmoArtMajors.setDepartmentId(danmoArtContent.getId());
                danmoArtMajors.setCollegesId(id);
                danmoArtMajorsMapper.insertDanmoArtMajors(danmoArtMajors);
            }

        }
    }
    /**
     * 修改书画院校
     *
     * @param danmoArtColleges 书画院校
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateDanmoArtColleges(DanmoArtColleges danmoArtColleges) {
        try {
            // 获取当前登录用户，若未登录则直接返回
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return Result.warn("请登录");
            }

            // 校验传入的参数是否合法
            Result validationResult = validateDanmoTrainingInformation(danmoArtColleges);
            if (validationResult != null) {
                return validationResult;
            }

            // 更新修改时间
            danmoArtColleges.setUpdateTime(DateUtils.getNowDate());

            // 执行删除和插入操作
            if (!updateDanmoArtDoors(danmoArtColleges) || !updateDanmoArtCollegesCharacteristics(danmoArtColleges)) {
                return Result.error("修改失败，操作未完全成功");
            }

            // 更新丹墨艺术院校信息
            int updateCount = danmoArtCollegesMapper.updateDanmoArtColleges(danmoArtColleges);


                DanmoArtDepartments danmoArtDepartments1 = new DanmoArtDepartments();
                danmoArtDepartments1.setCollegeId(danmoArtColleges.getId());
                List<DanmoArtDepartments> danmoArtDepartments2 = danmoArtDepartmentsMapper.selectDanmoArtDepartmentsList(danmoArtDepartments1);
                List<Long> idList = new ArrayList<>();
                for (DanmoArtDepartments artDepartments : danmoArtDepartments2) {
                    idList.add(artDepartments.getId());
                }
                danmoArtDepartmentsMapper.deleteDanmoArtDepartmentsByIds(idList.toArray(new Long[0]));

            List<DanmoArtDepartments> danmoDanmoArtDepartmentsList = danmoArtColleges.getDanmoDanmoArtDepartmentsList();
            processMajors(danmoArtColleges.getId(), danmoDanmoArtDepartmentsList);

            if (updateCount > 0) {
                return Result.success(updateCount, "修改成功");
            } else {
                return Result.error("未做任何修改");
            }
        } catch (Exception e) {
            // 更详细的异常捕获
            log.error("修改DanmoArtColleges失败", e);
            return Result.error("修改失败，系统发生异常");
        }
    }

    /**
     * 更新艺术院校的艺术门数据
     */
    private boolean updateDanmoArtDoors(DanmoArtColleges danmoArtColleges) {
        try {
            // 删除现有的门信息
            danmoArtCollegesMapper.deleteDanmoArtDoorByCollegesId(danmoArtColleges.getId());
            // 插入新的门信息
            insertDanmoArtDoor(danmoArtColleges);
            return true;
        } catch (Exception e) {
            log.error("更新艺术门信息失败", e);
            return false;
        }
    }

    /**
     * 更新艺术院校的特色数据
     */
    private boolean updateDanmoArtCollegesCharacteristics(DanmoArtColleges danmoArtColleges) {
        try {
            // 删除现有的特色信息
            deleteDanmoArtCollegesCharacteristics(danmoArtColleges);
            // 插入新的特色信息
            insertDanmoArtCollegesCharacteristics(danmoArtColleges, danmoArtColleges.getId());
            return true;
        } catch (Exception e) {
            log.error("更新艺术院校特色信息失败", e);
            return false;
        }
    }



    /**
     * 批量删除书画院校
     *
     * @param ids 需要删除的书画院校主键
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteDanmoArtCollegesByIds(Long[] ids) {
        try {

            danmoArtCollegesMapper.deleteDanmoArtDoorByCollegesIds(ids);
            danmoArtCollegesCharacteristicsMapper.deleteArtCollegesCharacteristicsByCollegesIds(ids);
            return Result.success(danmoArtCollegesMapper.deleteDanmoArtCollegesByIds(ids), "删除成功");
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }

    /**
     * 删除书画院校信息
     *
     * @param id 书画院校主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoArtCollegesById(Long id) {
        danmoArtCollegesMapper.deleteDanmoArtDoorByCollegesId(id);
        return danmoArtCollegesMapper.deleteDanmoArtCollegesById(id);
    }

    /**
     * 查看自己收藏的院校信息
     *
     * @param userid 用户id
     * @return 结果
     */
    @Override
    public Result selectUid(Long userid) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

//        查询用户的收藏材料
        List<DanmoArtMaterial> danmoCollectMaterials = danmoArtMaterialMapper.selectDanmoCollectMaterialByUserId(loginUser.getUserid());
        if (danmoCollectMaterials == null) {
            return Result.error("暂无收藏");
        }
//        使用 ArrayList 创建一个可变的集合
        List<DanmoArtColleges> danmoArtColleges = new ArrayList<>();
        for (DanmoArtMaterial danmoCollectMaterial : danmoCollectMaterials) {
            // 获取材料信息并添加到可变集合中
            List<DanmoArtColleges> artCollege = danmoArtCollegesMapper.selectDanmoArtCollegesById(danmoCollectMaterial.getCollegeId());
            for (DanmoArtColleges artColleges : artCollege) {
                danmoArtColleges.add(artColleges);

            }
        }
//        如果需要返回 danmoArtColleges，请返回这个列表
//        return danmoArtColleges;
//        如果还是需要返回原来的收藏材料，可以保持如下

        return Result.success(danmoArtColleges);
    }


    /**
     * 收藏书画院校
     *
     * @param collegeId 需要收藏的书画院校id
     */
    @Override
    public Result isCollect(Long collegeId, Long userId) {
        Boolean result = danmoArtMaterialMapper.selectDanmoCollectMaterialByIdAndUserId(userId, collegeId);
        boolean isCollected = (result != null) ? result : false; // 当result为null时使用false
        if (isCollected) {
            return Result.success(1, "用户已收藏");
        }
        DanmoArtMaterial danmoArtMaterial = new DanmoArtMaterial();
        danmoArtMaterial.setUserId(userId);
        danmoArtMaterial.setWhetherToCollect("true");
        danmoArtMaterial.setCollegeId(collegeId);
        danmoArtMaterialMapper.insertDanmoArtMaterial(danmoArtMaterial);
        return Result.success(1, "收藏成功");
    }

    @Override
    public Result removeArtCollectionColleges(Long[] ids, Long userId) {
        for (Long id : ids) {
            Boolean result = danmoArtMaterialMapper.selectDanmoCollectMaterialByIdAndUserId(userId, id);
            boolean isCollected = (result != null) ? result : false; // 当result为null时使用false
            if (!isCollected) {
                return Result.error("取消失败");
            }
        }
        danmoArtMaterialMapper.deleteDanmoArtMountFavoriteByIds(ids, userId);
        return Result.success(1,"取消成功");
    }

    @Autowired
    private DanmoArtCharacteristicsServiceImpl danmoArtCharacteristicsService;
    @Override
    public List<DanmoArtColleges> queryColleges(DanmoArtCollegesReq req) {

        // 第一步：根据特色条件查询符合的院校ID列表
        List<Long> danmoArtCollegesCharacteristicsList = req.getDanmoArtCollegesCharacteristicsList();

        // 如果传入的特色条件为空，则查询所有院校
        if (danmoArtCollegesCharacteristicsList == null) {
            danmoArtCollegesCharacteristicsList = new ArrayList<>();  // 设置为空列表
        }

        // 查询符合特色条件的院校ID列表
        List<Long> collegeIds = danmoArtCharacteristicsService.selectDanmoArtCollegesCharacteristicsList(danmoArtCollegesCharacteristicsList);

        // 如果没有符合特色条件的院校，直接返回空列表
        if (collegeIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 第二步：根据办学类型、办学层次等条件查询院校
        return queryCollegesByFilters(collegeIds, req.getSchoolType(), req.getSchoolLevel());
    }

    @Override
    public Map<String, List<DepartmentDTO>> selectDepartmentsList(Long id) {
        List<DepartmentDTO> departmentList = new ArrayList<>();

        // 查询所有学院
        List<DanmoArtDepartments> danmoArtDepartments = danmoArtDepartmentsMapper.selectDepartList(id);

        // 遍历每个学院
        for (DanmoArtDepartments department : danmoArtDepartments) {
            // 查询该学院下的所有专业
            List<DanmoArtMajors> majorsList = danmoArtMajorsMapper.selectMajorsList(department.getId());
            String departmentName = department.getName();

            // 存储该学院下的所有专业信息
            List<MajorDTO> majorDTOList = new ArrayList<>();
            for (DanmoArtMajors major : majorsList) {
                MajorDTO majorDTO = new MajorDTO(major.getMajorId(),major.getMajorName(), major.getDegree());
                majorDTOList.add(majorDTO);
            }

            // 创建学院DTO并添加到列表
            DepartmentDTO departmentDTO = new DepartmentDTO(departmentName, majorDTOList);
            departmentList.add(departmentDTO);
        }

        // 构建最终返回的Map结构
        Map<String, List<DepartmentDTO>> result = new HashMap<>();
        result.put("list", departmentList);

        return result;
    }

    public List<DanmoArtColleges> queryCollegesByFilters(List<Long> collegeIds, List<Long> schoolTypes, List<Long> schoolLevels) {
        // 如果办学类型或办学层次为空，传入null而不是空列表，避免错误的查询
        if (schoolTypes == null || schoolTypes.isEmpty()) {
            schoolTypes = null;  // 设置为空，以便在 SQL 中忽略该条件
        }
        if (schoolLevels == null || schoolLevels.isEmpty()) {
            schoolLevels = null;  // 设置为空，以便在 SQL 中忽略该条件
        }

        // 调用Mapper方法执行查询
        return danmoArtCollegesMapper.queryCollegesByFilters(collegeIds, schoolTypes, schoolLevels);
    }



    /**
     * 新增书画院校门头信息
     *
     * @param danmoArtColleges 书画院校对象
     */
    public void insertDanmoArtDoor(DanmoArtColleges danmoArtColleges) {
        List<DanmoArtDoor> danmoArtDoorList = danmoArtColleges.getDanmoArtDoorList();
        Long id = danmoArtColleges.getId();
        if (StringUtils.isNotNull(danmoArtDoorList)) {
            List<DanmoArtDoor> list = new ArrayList<DanmoArtDoor>();
            for (DanmoArtDoor danmoArtDoor : danmoArtDoorList) {
                danmoArtDoor.setCollegesId(id);
                list.add(danmoArtDoor);
            }
            if (list.size() > 0) {
                danmoArtCollegesMapper.batchDanmoArtDoor(list);
            }
        }
    }

    /**
     * 新增院校与校园特色关联表信息
     *
     * @param danmoArtColleges 书画院校对象
     * @param id
     */
    private void insertDanmoArtCollegesCharacteristics(DanmoArtColleges danmoArtColleges, Long id) {
        List<DanmoArtCollegesCharacteristics> danmoArtCollegesCharacteristicsList = danmoArtColleges.getDanmoArtCollegesCharacteristicsList();
        if (null!=danmoArtCollegesCharacteristicsList  || danmoArtCollegesCharacteristicsList.size() > 0) {
            for (DanmoArtCollegesCharacteristics danmoArtCollegesCharacteristics : danmoArtCollegesCharacteristicsList) {
                danmoArtCollegesCharacteristics.setCollegesId(id);
                danmoArtCollegesCharacteristicsMapper.addDanmoArtCollegesCharacteristi(danmoArtCollegesCharacteristics);
            }
        }
    }

    /**
     * 删除院校与校园特色关联表信息
     *
     * @param danmoArtColleges 书画院校对象
     */
    private void deleteDanmoArtCollegesCharacteristics(DanmoArtColleges danmoArtColleges) {
        danmoArtCollegesCharacteristicsMapper.deleteDanmoArtCollegesCharacteristicsList(danmoArtColleges.getId());
    }

    private Result validateDanmoTrainingInformation(DanmoArtColleges danmoArtColleges) {
        if (danmoArtColleges == null) {
            return Result.error("信息不能为空");
        }
        if (danmoArtColleges.getName() == null || danmoArtColleges.getName().isEmpty()) {
            return Result.error("请输入学校名称");
        }
        if (danmoArtColleges.getOfficialWebsite() == null || danmoArtColleges.getOfficialWebsite().isEmpty()) {
            return Result.error("请输入官网");
        }
        if (danmoArtColleges.getPhone() == null || danmoArtColleges.getPhone().isEmpty()) {
            return Result.error("请输入电话");
        }
        if (danmoArtColleges.getDetailAddress() == null || danmoArtColleges.getDetailAddress().isEmpty()) {
            return Result.error("请输入详细地址");
        }

        if (danmoArtColleges.getSummarized() == null || danmoArtColleges.getSummarized().isEmpty()) {
            return Result.error("请输入概括");
        }
        if (danmoArtColleges.getSchoolLevel() == null) {
            return Result.error("请选择办学层次");
        }

        return null;
    }


}
